<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  
  <link rel="shortcut icon" href="../../img/favicon.ico">
  <title>Send File - Forge Networking Remastered</title>
  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" href="../../css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../css/theme_extra.css" type="text/css" />
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">
  
  <script>
    // Current page data
    var mkdocs_page_name = "Send File";
    var mkdocs_page_input_path = "BasicNetworkSamples/send-file.md";
    var mkdocs_page_url = null;
  </script>
  
  <script src="../../js/jquery-2.1.1.min.js" defer></script>
  <script src="../../js/modernizr-2.8.3.min.js" defer></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script> 
  
</head>

<body class="wy-body-for-nav" role="document">

  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
      <div class="wy-side-nav-search">
        <a href="../.." class="icon icon-home"> Forge Networking Remastered</a>
        <div role="search">
  <form id ="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" title="Type search term here" />
  </form>
</div>
      </div>

      <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
	<ul class="current">
	  
          
            <li class="toctree-l1">
		
    <span class="caption-text">Home</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../..">User Manual (Forge Networking Remastered)</a>
                </li>
                <li class="">
                    
    <a class="" href="../../authoritative-design/">Authoritative Design</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Getting Started</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../GettingStarted/getting-started/">Getting Started</a>
                </li>
                <li class="">
                    
    <a class="" href="../../GettingStarted/basic-moving-cube-example/">Basic Moving Cube Example</a>
                </li>
                <li class="">
                    
    <a class="" href="../../GettingStarted/basic-rpc-example/">Basic RPC Example</a>
                </li>
                <li class="">
                    
    <a class="" href="../../GettingStarted/basic-instantiation-example/">Basic Instantiation Example</a>
                </li>
                <li class="">
                    
    <a class="" href="../../GettingStarted/jump-start-guide/">Jump Start Guide</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Network Contract Wizard (NCW)</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../NetworkContractWizard/network-contract-wizard-ncw/">Network Contract Wizard (NCW)</a>
                </li>
                <li class="">
                    
    <a class="" href="../../NetworkContractWizard/extending-generated-classes/">Extending Generated Classes</a>
                </li>
                <li class="">
                    
    <a class="" href="../../NetworkContractWizard/name-collision-issues/">Name Collision Issues</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Network Object</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../NetworkObject/changing-ownership/">Changing Ownership</a>
                </li>
                <li class="">
                    
    <a class="" href="../../NetworkObject/destroying-the-network-object/">Destroying the Network Object</a>
                </li>
                <li class="">
                    
    <a class="" href="../../NetworkObject/fields/">Fields</a>
                </li>
                <li class="">
                    
    <span class="caption-text">Remote Procedure Calls (RPCs)</span>
    <ul class="subnav">
                <li class="toctree-l3">
                    
    <a class="" href="../../NetworkObject/RemoteProcedureCalls/remote-procedure-calls/">Remote Procedure Calls</a>
                </li>
                <li class="toctree-l3">
                    
    <a class="" href="../../NetworkObject/RemoteProcedureCalls/buffered-rpcs/">Buffered RPCs</a>
                </li>
                <li class="toctree-l3">
                    
    <a class="" href="../../NetworkObject/RemoteProcedureCalls/sending-rpc-to-a-single-player/">Sending RPC to a Single Player</a>
                </li>
                <li class="toctree-l3">
                    
    <a class="" href="../../NetworkObject/RemoteProcedureCalls/rpcargs-and-rpcinfo-structs/">RpcArgs and RpcInfo Structs</a>
                </li>
                <li class="toctree-l3">
                    
    <a class="" href="../../NetworkObject/RemoteProcedureCalls/rpc-validation-by-server/">RPC Validation by Server</a>
                </li>
                <li class="toctree-l3">
                    
    <a class="" href="../../NetworkObject/RemoteProcedureCalls/replacing-previous-buffered-rpcs/">Replacing Previous Buffered RPCs</a>
                </li>
                <li class="toctree-l3">
                    
    <a class="" href="../../NetworkObject/RemoteProcedureCalls/clearing-buffered-rpcs/">Clearing Buffered RPCs</a>
                </li>
    </ul>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Unity Integration</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../UnityIntegration/gameobject-execution-order/">GameObject Execution Order</a>
                </li>
                <li class="">
                    
    <a class="" href="../../UnityIntegration/network-instantiation/">Network Instantiation</a>
                </li>
                <li class="">
                    
    <a class="" href="../../UnityIntegration/threading-in-unity/">Threading in Unity</a>
                </li>
                <li class="">
                    
    <a class="" href="../../UnityIntegration/main-threading-rpcs/">Main Threading RPCs</a>
                </li>
                <li class="">
                    
    <a class="" href="../../UnityIntegration/running-unity-specific-code-on-the-main-thread/">Running Unity specific code on the main thread</a>
                </li>
                <li class="">
                    
    <a class="" href="../../UnityIntegration/network-start/">Unity Integration Network Start</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Basic Network Samples</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../server-hosting-code/">Server Hosting Code</a>
                </li>
                <li class="">
                    
    <a class="" href="../client-connecting-code/">Client Connecting Code</a>
                </li>
                <li class="">
                    
    <a class="" href="../server-disconnect-client-code/">Server Disconnect Client Code</a>
                </li>
                <li class="">
                    
    <a class="" href="../ban-client-code/">Ban Client Code</a>
                </li>
                <li class="">
                    
    <a class="" href="../send-binary-frame/">Send Binary Frame</a>
                </li>
                <li class=" current">
                    
    <a class="current" href="./">Send File</a>
    <ul class="subnav">
            
    <li class="toctree-l3"><a href="#send-file">Send File</a></li>
    
        <ul>
        
            <li><a class="toctree-l4" href="#the-setup">The Setup</a></li>
        
            <li><a class="toctree-l4" href="#preparing-to-run">Preparing to run</a></li>
        
        </ul>
    

    </ul>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Scene Navigation</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../SceneNavigation/loading-scenes/">Loading Scenes</a>
                </li>
                <li class="">
                    
    <a class="" href="../../SceneNavigation/scene-events/">Scene Events</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">NetWorker</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../NetWorker/temporarily-blocking-connections/">Temporarily Blocking Connections</a>
                </li>
                <li class="">
                    
    <a class="" href="../../NetWorker/thread-safe-player-iteration/">Thread Safe Player Iteration</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Master Server</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../MasterServer/quick-start/">Master Server Quick Start</a>
                </li>
                <li class="">
                    
    <a class="" href="../../MasterServer/connecting-to-master-server/">Connecting to Master Server</a>
                </li>
                <li class="">
                    
    <a class="" href="../../MasterServer/getting-host-list/">Getting Host List From Master Server</a>
                </li>
                <li class="">
                    
    <a class="" href="../../MasterServer/windows-server-firewall-setup/">Windows Server Firewall Setup</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Web Server</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../WebServer/jumpstart/">Web Server Jumpstart</a>
                </li>
                <li class="">
                    
    <a class="" href="../../WebServer/extending-with-mvc/">Web Server Extending With MVC</a>
                </li>
                <li class="">
                    
    <a class="" href="../../WebServer/command-plugins/">Web Server Command Plugins</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <span class="caption-text">Troubleshooting</span>
    <ul class="subnav">
                <li class="">
                    
    <a class="" href="../../Troubleshooting/troubleshooting/">Troubleshooting</a>
                </li>
                <li class="">
                    
    <a class="" href="../../Troubleshooting/throttling-network-internal/">Throttling Network Internal</a>
                </li>
    </ul>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../connection-cycle-events/">Events</a>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../rewinding/">Rewinding</a>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../network-logging/">Debugging</a>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../working-with-multiple-sockets/">Working With Multiple Sockets</a>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../nat-hole-punching/">NAT Hole Punching</a>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../lan-discovery/">LAN Discovery</a>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../offline-mode/">Offline Mode</a>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../lobby/">Lobby System</a>
	    </li>
          
            <li class="toctree-l1">
		
    <a class="" href="../../adding-and-updating-docs/">Contributing</a>
	    </li>
          
        </ul>
      </div>
      &nbsp;
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" role="navigation" aria-label="top navigation">
        <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
        <a href="../..">Forge Networking Remastered</a>
      </nav>

      
      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
    <li><a href="../..">Docs</a> &raquo;</li>
    
      
        
          <li>Basic Network Samples &raquo;</li>
        
      
    
    <li>Send File</li>
    <li class="wy-breadcrumbs-aside">
      
    </li>
  </ul>
  <hr/>
</div>
          <div role="main">
            <div class="section">
              
                <h1 id="send-file">Send File</h1>
<p>Forge Networking works with all kinds of data, but that doesn't exclude sending files across the network. At the end of the day, files are just an array of bytes (<code>byte[]</code>) and by now, you probably know you can send that stuff over the network with Forge Networking. So let's get started with a simple desktop-&gt;desktop file transfer shall we!</p>
<h2 id="the-setup">The Setup</h2>
<p>To get started we are going to need to setup our environment so that we can quickly and easily test our code. So let's open up a project with Forge Networking imported into it to get started.</p>
<p>1) Download the <code>deal-with-it.jpg</code> image (cat image below)
2) Open project with Forge Networking imported
3) Create a folder named <code>FileTransfer</code>
4) Copy the <code>deal-with-it.jpg</code> image into the <code>FileTransfer</code> folder
5) Create a new scene and save it into the <code>FileTransfer</code> folder named <code>FileTransferTest</code>
6) Create a C# script in the <code>FileTransfer</code> folder named <code>SendThatFile</code>
7) Open that script in your favorite editor
8) Put the following code into the script</p>
<p><img alt="Deal With It!" src="https://raw.githubusercontent.com/BeardedManStudios/ForgeNetworkingRemastered/develop/docs/mkdocs/docs/images/deal-with-it.jpg" /></p>
<p><em>Note that this code is not optimized but made simple for quick understanding</em></p>
<pre><code class="csharp">using BeardedManStudios;
using BeardedManStudios.Forge.Networking;
using BeardedManStudios.Forge.Networking.Frame;
using BeardedManStudios.Forge.Networking.Unity;
using System.IO;
using UnityEngine;

public class SendThatFile : MonoBehaviour
{
    public string filePath;
    private bool sentFile;

    private void Start()
    {
        NetworkManager.Instance.Networker.binaryMessageReceived += ReceiveFile;
    }

    private void ReceiveFile(NetworkingPlayer player, Binary frame)
    {
        // We are looking to read a very specific message
        if (frame.GroupId != MessageGroupIds.START_OF_GENERIC_IDS + 1)
            return;

        Debug.Log(&quot;Reading file!&quot;);

        // Read the string from the beginning of the payload
        string fileName = frame.StreamData.GetBasicType&lt;string&gt;();

        Debug.Log(&quot;File name is &quot; + fileName);

        if (File.Exists(fileName))
        {
            Debug.LogError(&quot;The file &quot; + fileName + &quot; already exists!&quot;);
            return;
        }

        // Write the rest of the payload as the contents of the file and
        // use the file name that was extracted as the file's name
        File.WriteAllBytes(fileName, frame.StreamData.CompressBytes());
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) &amp;&amp; !sentFile)
        {
            sentFile = true;

            // Throw an error if this is not the server
            var networker = NetworkManager.Instance.Networker;
            if (!networker.IsServer)
            {
                Debug.LogError(&quot;Only the server can send files in this example!&quot;);
                return;
            }

            // Throw an error if the file does not exist
            if (!File.Exists(filePath))
            {
                Debug.LogError(&quot;The file &quot; + filePath + &quot; could not be found&quot;);
                return;
            }

            // Prepare a byte array for sending
            BMSByte allData = new BMSByte();

            // Add the file name to the start of the payload
            ObjectMapper.Instance.MapBytes(allData, Path.GetFileName(filePath));

            // Add the data to the payload
            allData.Append(File.ReadAllBytes(filePath));

            // Send the file to all connected clients
            Binary frame = new Binary(
                networker.Time.Timestep,                    // The current timestep for this frame
                false,                                      // We are server, no mask needed
                allData,                                    // The file that is being sent
                Receivers.Others,                           // Send to all clients
                MessageGroupIds.START_OF_GENERIC_IDS + 1,   // Some random fake number
                networker is TCPServer);

            if (networker is UDPServer)
                ((UDPServer)networker).Send(frame, true);
            else
                ((TCPServer)networker).SendAll(frame);
        }
    }
}
</code></pre>

<h2 id="preparing-to-run">Preparing to run</h2>
<p>1) Open the Unity build menu
2) Add the <code>MultiplayerMenu</code> scene as the first scene
3) Add the <code>FileTransferTest</code> as the second scene
4) Open the Player Settings...
5) Turn on run in background
6) Open the <code>FileTransferTest</code> scene
7) Select the camera or any object in the scene
8) Add the <code>SendThatFile</code> script to the object
9) Update the <code>File Path</code> field on the script to have the full path to the <code>deal-with-it.jpg</code> image inside of the <code>FileTransfer</code> folder
10) Save the scene
11) Build and Run
12) Open 2 instances of the game
13) Set one to be the server then connect with the other
14) Press the spacebar on the server
15) Go into the build folder for the player and then go up a directory, you will notice a <code>deal-with-it.jpg</code> has been created</p>
              
            </div>
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="../../SceneNavigation/loading-scenes/" class="btn btn-neutral float-right" title="Loading Scenes">Next <span class="icon icon-circle-arrow-right"></span></a>
      
      
        <a href="../send-binary-frame/" class="btn btn-neutral" title="Send Binary Frame"><span class="icon icon-circle-arrow-left"></span> Previous</a>
      
    </div>
  

  <hr/>

  <div role="contentinfo">
    <!-- Copyright etc -->
    
  </div>

  Built with <a href="http://www.mkdocs.org">MkDocs</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
      
        </div>
      </div>

    </section>

  </div>

  <div class="rst-versions" role="note" style="cursor: pointer">
    <span class="rst-current-version" data-toggle="rst-current-version">
      
      
        <span><a href="../send-binary-frame/" style="color: #fcfcfc;">&laquo; Previous</a></span>
      
      
        <span style="margin-left: 15px"><a href="../../SceneNavigation/loading-scenes/" style="color: #fcfcfc">Next &raquo;</a></span>
      
    </span>
</div>
    <script>var base_url = '../..';</script>
    <script src="../../js/theme.js" defer></script>
      <script src="../../search/main.js" defer></script>

</body>
</html>
